package com.googlecode.aleverr.yafotkiclient.api;

import android.util.Log;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.xpath.*;
import java.util.ArrayList;
import java.util.List;

public abstract class AbstractCollection<E> {
    
    private static final String TAG = "AbstractCollection";

    private static final XPathExpression ENTRIES_EXPRESSION;

    static {
        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression expression = null;
        try {
            expression = xPath.compile("/feed/entry");
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } finally {
            ENTRIES_EXPRESSION = expression;
        }
    }

    protected final List<E> entries = new ArrayList<E>();

    protected abstract E processEntry(Node entryNode);

    protected void processUrl(String address, String accessToken) {
        Document document = Utils.obtainDocument(address, accessToken);
        if (document != null) {
            try {
                NodeList nodes = (NodeList) ENTRIES_EXPRESSION.evaluate(document, XPathConstants.NODESET);
                for (int i = 0; i < nodes.getLength(); i++) {
                    E entry = processEntry(nodes.item(i));
                    if (entry != null) {
                        entries.add(entry);
                    }
                }
            } catch (XPathExpressionException e) {
                Log.e(TAG, e.getMessage(), e);
            }
        }
    }

    public List<E> getEntries() {
        return entries;
    }
}
